package com.bw.demoseckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.demoseckill.entity.TbAdmin;
import com.bw.demoseckill.entity.TbUser;
import com.bw.demoseckill.mapper.AdminMapper;
import com.bw.demoseckill.mapper.UserMapper;
import com.bw.demoseckill.service.AdminService;
import com.bw.demoseckill.service.UserService;
import com.bw.demoseckill.utils.JwtTokenUtils;
import com.bw.demoseckill.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * @author Administrator
 */
@Service
@Slf4j
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public ResponseResult doLogin(String adminName, String adminPwd) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();
        //查询管理人员
        TbAdmin admin = adminMapper.selectOne(new QueryWrapper<TbAdmin>()
                .eq("admin_name",adminName));
        //管理不存在
        if(admin == null) {
            result.setSuccess(false);
            result.setMessage("管理人员不存在");
            return result;
        }

        //判断密码
        String password = adminPwd + "." +admin.getAdminSalt();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!admin.getAdminPwd().equals(md5Password)){
            result.setSuccess(false);
            result.setMessage("密码不正确");
            return result;
        }

        //生成token
        String token = JwtTokenUtils.makeToken(admin.getId(), admin.getAdminName(), "admin");
        resultMap.put("admin", admin);
        resultMap.put("token", token);
        result.setResult(resultMap);
        return result;
    }
}
